package com.demo.chatback.component;

import com.demo.chatback.api.CommonController;
import com.demo.chatback.api.CommonResult;
import com.demo.chatback.constant.SystemConstant;
import com.demo.chatback.util.RedisUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Set;

/**
 * @Description 聊天接口
 * @Author 小乌龟
 * @Date 2022/12/15 19:18
 */
@RestController
@RequestMapping("/chat")
@Validated
@Slf4j
public class ChatController extends CommonController {

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/getChatList")
    public CommonResult<List<Object>> getChatList(@RequestParam @NotBlank(message = "获取未读消息异常") String userId){
        return process(()->{
            //1.redis 获取出发生者待接收消息 并清除
            String getChatRedisKey= SystemConstant.REDIS_KEY_CHAT + userId;
            if(redisUtil.hasKey(getChatRedisKey)){
                List<Object> getChatInfoList = redisUtil.lGet(getChatRedisKey, SystemConstant.NUM_ZERO, SystemConstant.NUM_NEGATIVE_ONE);
                //2.返回给前端待接收消息
                log.info("获取到连接用户待收消息====={}===",getChatInfoList.toString());
                redisUtil.del(getChatRedisKey);
                return getChatInfoList;
            }
            return null;
        });
    }

    @GetMapping("/getChatSender")
    public CommonResult<Set<Object>> getChatSender(@RequestParam @NotBlank(message = "获取未读消息异常") String userId){
        return process(()->{
            //1.redis 获取出发生者待接收消息 并清除
            String getChatRedisKey= SystemConstant.REDIS_KEY_SENDER + userId;
            if(redisUtil.hasKey(getChatRedisKey)){
                Set<Object> getChatInfoList = redisUtil.sGet(getChatRedisKey);
                //2.返回给前端待接收消息
                log.info("获取到连接用户待收发送者id====={}===",getChatInfoList.toString());
                redisUtil.del(getChatRedisKey);
                return getChatInfoList;
            }
            return null;
        });
    }
}
